package model;

import sql.Db;
import sql.ResultSetHandler;

import java.sql.ResultSet;

public class UserModel {
    
    public String name, email, city, state, major, sex;
    public String userId;

    public UserModel() {
        userId = "";
    }

    /**
     * Construct a user from a result set.
     * @param rs
     */
    public UserModel(ResultSet rs) {
        try {
            userId = rs.getString("id");

            name = rs.getString("name");
            email = rs.getString("email");
            city = rs.getString("city");
            state = rs.getString("state");
            major = rs.getString("major");
            sex = rs.getString("sex");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Commit this model to the db. If ID exists, then it's an update, otherwise it's an insert.
     */
    public void commit() {
        Db db = Db.getDb();
        try{
            if(userId.equals("")){
            	db.executeNonQuery(
                    "INSERT INTO post(name, city, state, major, email, sex)" +
                    "\nVALUES('" +
                        name + "', '" +
                        city + "', '" +
                        state + "', '" +
                        major + "', '" +
                        email + "', '" +
                        sex + "')",

                    new ResultSetHandler() {
                        @Override
                        public void handleResult(ResultSet rs) {
                            try {
                                if (rs.next()) {
                                    userId = rs.getString(1);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                );
            }else{
            	db.executeNonQuery(
                    "UPDATE post SET " +
                    "name = " + name +
                    ", city = " + city +
                    ", state = " + state +
                    ", major = " + major +
                    ", email = " + email +
                    ", sex = " + sex +
                    "WHERE userID = " + userId,

                    new ResultSetHandler() {
                        @Override
                        public void handleResult(ResultSet rs) {

                        }
                    }
                );
            }
    	}catch (Exception e){
            e.printStackTrace();
    	}
    }

}
